// pages/pay/pay.js
var that,
  api = new (require('../../utils/api.js')),
  headimg = api.getimgurl(),
  app = getApp(),
util = new (require('../../utils/util.js'));
Page({
  /**
   * 页面的初始数据
   */
  data: {
    address:"",
    noaddress:!0,
    nowdate:'',
    describe:"",
    date:"",
    borrowDate:"",
    backDate:"",
    ismember:'',
    ispay:!1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    
    this.getaddress();
    this.getsetting();
    this.getbooks();
  },
  inputchange(e) {
    var proval = {}, { prop } = e.target.dataset;
    proval[prop] = e.detail.value;
    // console.log(proval,prop);
    this.setData(proval);

  },
  getdate(day){
    let nowdate = new Date(),
    date = util.formatDate(nowdate),
    startdate = util.todate(nowdate),
    backDate = util.mathChangeDate(nowdate,"+",day),
    enddate = util.toDate(backDate),
    borrowDate = (Date.parse(nowdate))/1000;
    console.log(backDate, borrowDate,nowdate);
    this.setData({ nowdate,startdate,enddate,date,borrowDate,backDate});
  },
  bindDateChange(e) {
    let date = Date.parse(e.detail.value),
    day = this.data.setting.borrowdate;
    date = new Date(date);
    let startdate = util.todate(date),
    borrowDate = (Date.parse(date))/1000,
    backDate = util.mathChangeDate(date, "+", day),
    enddate = util.toDate(backDate);
    console.log(backDate,borrowDate);
    this.setData({ date: e.detail.value,startdate,enddate,borrowDate,backDate});
  },
  getbooks(){
    let ids = wx.getStorageSync("payids");
    ids=ids.join(',');
    console.log(ids);
    api.getbooks({ids},res=>{
      if(res.data.issuccess==1){
        console.log(res.data.data,'res.data.data')
        this.formatdata(res.data.data);
        this.setData({ goodsid:ids });
      }
    }); 
    wx.removeStorageSync("payids");
  },
 
    formatdata(list) {
      console.log(list,'paylist')
      list.forEach((x, i) => {
        let {ismember }= that.data
        if (x.thumbPicPath.indexOf("http") == -1) {
          x.thumbPicPath = headimg + x.thumbPicPath;
        }
        // x.detaillist = x.detaillist.split(',');
        x.labels = x.labels.split(',');
        // if (x.detaillist.length > 0) {
        //   x.detaillist.forEach((y, i) => {
        //     if (y.indexOf("http") == -1) {
        //       x.detaillist[i] = headimg + x.detaillist[i];
        //     }
        //   });
        // }
      });
      this.setData({ list });
 
  },
  getsetting(){
    let setting = wx.getStorageSync("setting");
    setting.deposit =setting.deposit/100;
    setting.rent = setting.rent/100;
    let total = setting.deposit + setting.rent;
    this.setData({setting,total});
    this.getdate(setting.borrowdate);
  },
  getaddress(){
    console.log('getaddressgetaddress');
    
      let flag = !0;
      api.getaddresslist(res => {
        if(res.data.issuccess==1){
          let list = res.data.list;
          if(list.length>0){
            list.forEach((x,i)=>{
              if(x.ischeck==1){
                flag = !1;
                let address = list[i];
                this.setData({ address, noaddress: !1 });
              }
            });    
          }
          if(flag){
            let address = res.data.list[0];
            if(address){
              this.setData({ address, noaddress: !1 });
            }else{
              this.setData({noaddress:!0});
            }
            
          }
          
        }
      });
    
  },
  sub(){
    let {ispay}=that.data
    if(ispay){
      return;
    }else{
      that.setData({ispay:!0})
      let type=wx.getStorageSync('type')
      console.log(type,'type');
      console.log(this.data.address, "address");
      //这是一个json对象
    var addressinfo = JSON.stringify(this.data.address)
      let {describe,goodsid,setting,address,total,borrowDate,backDate} = this.data,deposit = setting.deposit*100,
        addressid = address.id, openid = wx.getStorageSync("openid");
        total = total*100;
        let data = { describe, goodsid, deposit, total, addressid,borrowDate,backDate,addressinfo,type:'BOOKS' };
      if(address==""){
        wx.showToast({
          icon:"none",
          title: '请添加地址',
        })
      }
      if(goodsid!=''){
        api.addorder(data,res=>{
          if(res.data.issuccess==1){
            let ordernumber = res.data.ordernumber,
            subdata = {ordernumber,openid,total};

            let idlength= goodsid.split(",")
            // console.log(subdata,'subdata');
            api.prepay(subdata, res => {
              api.delcart({ ids: goodsid },res=>{
                if (res.data.issuccess == 1) {
                  let cartids = wx.getStorageSync("cartids");
                  cartids.splice(0, idlength.length)
                  wx.setStorageSync("cartids", cartids);
                  app.badege(cartids);
                }
              })
              // console.log(res,'2222');
              if (res.succ == 1) {
                if(type=="CONSUMER"){
                  api.setvip(res =>{
                    if(res.data.issuccess == 1){
                      console.log(1111)
                    }
                  })
                }
                api.afterpaysucc({ ordernumber, cost: total, goodsid, deposit }, res => {
                  // console.log(3333,'3333');
              if (res.data.issuccess == 1) {
                    wx.requestSubscribeMessage({
                      tmplIds: ['RxoJIrjvpTBHGObvr2AhXnRE9H-ABO1QhM6PTVOqPwM'],
                      success: (res) => {
                        console.log('订阅结果');
                        console.log(res);
                        if (res.errMsg == 'requestSubscribeMessage:ok') {
                          let status = res['RxoJIrjvpTBHGObvr2AhXnRE9H-ABO1QhM6PTVOqPwM'];
                          console.log(status);
                        } else {
                          wx.showModal({
                            showCancel: false,
                            title: '提示',
                            message: res.errMsg + ',请重新订阅！'
                          })
                        }
                      },
                      fail: ex => {
                        wx.showModal({
                          title: '提示',
                          message: JSON.stringify(ex),
                          showCancel: false
                        })
                      }
                    })    
                    wx.redirectTo({
                      url: '../order/order?o=0',
                    })
                  }
                })
              } else {
                wx.redirectTo({
                  url: '../order/order?o=0',
                })
              }
            })
            // api.pay(subdata,res=>{
            //   if(res.data.issuccess==1){
            //     let param = JSON.parse(res.data.res);
              
            //     wx.requestPayment({
            //       timeStamp: param.timeStamp,
            //       nonceStr: param.nonce_str,
            //       package: param.package,
            //       signType: 'MD5',
            //       paySign: param.paySign,
            //       success(res) {
            //         //删除购物车
            //         console.log("成功");
            //         api.afterpaysucc({ordernumber,cost:total,goodsid},res=>{
            //           if(res.data.issuccess==1){
            //             api.delcart({ ids:goodsid },res=>{
            //               if (res.data.issuccess == 1) {
            //                 wx.redirectTo({
            //                   url: '../order/order?o=0',
            //                 })
            //               }
            //             })
            //           }
            //         });
            //       },
            //       fail(res){
            //         api.delcart({ ids: goodsid }, res => {
            //           if (res.data.issuccess == 1) {
            //             wx.redirectTo({
            //               url: '../order/order?o=0',
            //             })
            //           }
            //         })
            //       }
                 
            //     })
            //   }
            // });
          }
        });
      }else{
        
      }
    }
  },
  
  toaddress(e){
    let {addreid} = e.currentTarget.dataset;
    
    if(addreid==undefined){ 
      addreid=-1;
    }
   
    wx.navigateTo({
      url: '../address/address?p=1&&addreid='+addreid,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.needgetaddress){
      this.setData({noaddress:!1});
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})